package com.atguigu.daijia.rules.service.impl;

import com.atguigu.daijia.model.form.rules.FeeRuleRequest;
import com.atguigu.daijia.model.form.rules.FeeRuleRequestForm;
import com.atguigu.daijia.model.vo.rules.FeeRuleResponse;
import com.atguigu.daijia.model.vo.rules.FeeRuleResponseVo;
import com.atguigu.daijia.rules.service.FeeRuleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FeeRuleServiceImpl implements FeeRuleService {
    @Resource
    private KieContainer kieContainer;

    /**
     * 计算订单费用
     */
    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm form) {
        // 封装输入对象
        FeeRuleRequest request = new FeeRuleRequest();
        BeanUtils.copyProperties(form, request);
        request.setStartTime(new DateTime(form.getStartTime()).toString("HH:mm:ss"));

        // 规则引擎计算
        KieSession kieSession = kieContainer.newKieSession();
        FeeRuleResponse response = new FeeRuleResponse();
        kieSession.setGlobal("feeRuleResponse", response);
        kieSession.insert(request);
        // 触发规则
        kieSession.fireAllRules();
        kieSession.dispose(); // 终止会话

        FeeRuleResponseVo vo = new FeeRuleResponseVo();
        BeanUtils.copyProperties(response, vo);
        return vo;
    }
}
